from typing import List 

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        # handle corner case 
        if l1 is None: 
            return l2 
        if l2 is None: 
            return l1 
        
        # determine merge head 
        mergeHead = None 
        if l1.val < l2.val: 
            mergeHead = l1 
            l1 = l1.next 
        else: 
            mergeHead = l2 
            l2 = l2.next 
        mergeTail = mergeHead 

        # traverse the lists 
        while l1 != None and l2 != None: 
            if l1.val < l2.val: 
                temp = l1 
                l1 = l1.next 
            else: 
                temp = l2 
                l2 = l2.next 
            mergeTail.next = temp 
            mergeTail = temp 
        
        if l1 != None: 
            mergeTail.next = l1 
        if l2 != None: 
            mergeTail.next = l2 

        return mergeHead 

if __name__ == "__main__":
    l1 = ListNode(1)
    l11 = ListNode(2)
    l12 = ListNode(4)
    l1.next = l11 
    l11.next = l12 

    l2 = ListNode(1)
    l21 = ListNode(3)
    l22 = ListNode(4)
    l2.next = l21 
    l21.next = l22

    s = Solution()
    result = s.mergeTwoLists(l1, l2)
    while result != None: 
        print(result.val)
        result = result.next
